package com.jwell.panrank.ui.activity

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.jwell.cargoapp.ui.base.MVPBaseActivity
import com.jwell.panrank.R
import com.jwell.panrank.contract.PreRegisterContract
import com.jwell.panrank.entity.SearchDriverBean
import com.jwell.panrank.entity.ValMsgDto
import com.jwell.panrank.model.PreRegisterModel
import com.jwell.panrank.presenter.PreRegisterPresenter
import com.jwell.panrank.tools.DataModel
import com.jwell.panrank.tools.RecyclerViewDivider
import com.jwell.panrank.ui.adapter.PreRegisterDriverAdapter
import com.jwell.panrank.ui.custom.LicensePlateUtils
import com.jwell.panrank.ui.dialog.PreRegisterDialog
import kotlinx.android.synthetic.main.activity_pre_register.*
import kotlinx.android.synthetic.main.pre_register_step1_layout.*
import kotlinx.android.synthetic.main.pre_register_step2_layout.*
import kotlinx.android.synthetic.main.toolbar.*
import java.util.*
import kotlin.concurrent.timerTask

/**
 * 预登记
 */
class PreRegisterActivity : MVPBaseActivity<PreRegisterPresenter>(), PreRegisterContract.View, View.OnClickListener {


    //控制步骤
    private var step = 1
    //选择物资名称
    private val CHOOSE_GOODS_NAME = 0
    //选择的货物是否可以标证除皮
    private var isOutOfSkin = false
    //选择发货单位
    private val CHOOSE_SEND_COM_NAME = 1
    //选择收货单位
    private val CHOOSE_RECEPT_COM_NAME = 2
    //选择司机
    private val CHOOSE_DRIVER = 3
    //货物代码
    private var orG_CODE: String? = null
    private var popupWindow: PopupWindow? = null
    private var requestData = PreRegisterModel.RequestData()
    private var driverInfoList = ArrayList<PreRegisterModel.DriverInfo>()
    private var driverInfoAdapter = PreRegisterDriverAdapter(driverInfoList)
    //是否可以选择或输入发货单位、收货单位
    private var isCanChooseSendCom = true
    private var isCanChooseReceiptCom = true

    override fun createPresenter(): PreRegisterPresenter? {
        return PreRegisterPresenter()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContentView(R.layout.activity_pre_register)
        initToolBar("预登记", true, null)
        setLabelSelected(true, false, false, false, false)
        setLabelSelected1(true, false, false)
        setListener()
        driverInfoList.add(PreRegisterModel.DriverInfo())
        step2_recyclerView.adapter = driverInfoAdapter
        step2_recyclerView.layoutManager = LinearLayoutManager(this)
        step2_recyclerView.addItemDecoration(RecyclerViewDivider(this, LinearLayoutManager.VERTICAL, resources.getDimensionPixelSize(R.dimen.dp_7), resources.getColor(R.color.background)))
    }

    private fun setListener() {
        ll_btn1.setOnClickListener(this)
        ll_btn2.setOnClickListener(this)
        rl_item11.setOnClickListener(this)
        rl_item12.setOnClickListener(this)
        rl_item13.setOnClickListener(this)
        rl_item14.setOnClickListener(this)
        rl_item15.setOnClickListener(this)
        rl_item16.setOnClickListener(this)
        rl_item21.setOnClickListener(this)
        rl_item22.setOnClickListener(this)
        rl_item23.setOnClickListener(this)
        text_goodsName.setOnClickListener(this)
        text_sendCom.setOnClickListener(this)
        text_receiptCom.setOnClickListener(this)
        toolbar_right_text_view.setOnClickListener(this)
        driverInfoAdapter.setChooseListener(object : PreRegisterDriverAdapter.ChooseListener {
            override fun chooseCarNum(position: Int) {
                val utils = LicensePlateUtils(this@PreRegisterActivity, popupWindow)
                utils.showInParentDown(ll_step2)
                utils.setLicenseSelectedListener { licenseNum ->
                    driverInfoList[position].carNum = licenseNum
                    presenter?.checkCarNum(licenseNum, position)
                    driverInfoAdapter.notifyDataSetChanged()
                }
            }

            override fun chooseDriver(position: Int) {
                val intent = Intent(this@PreRegisterActivity, SearchActivity::class.java)
                var bundle = Bundle()
                bundle.putInt("type", CHOOSE_DRIVER)
                bundle.putInt("driverPosition", position)
                bundle.putBoolean("canInput", true)
                intent.putExtras(bundle)
                startActivityForResult(intent, CHOOSE_DRIVER)
            }
        })
    }

    override fun onClick(v: View?) {
        var bundle = Bundle()
        when (v?.id) {
            R.id.toolbar_right_text_view -> {//新增调度司机
                driverInfoList.add(PreRegisterModel.DriverInfo())
                driverInfoAdapter.notifyDataSetChanged()
            }
            R.id.text_goodsName -> {
                val intent = Intent(this, SearchActivity::class.java)
                bundle.putInt("type", CHOOSE_GOODS_NAME)
                var canSelect=false
                if(rl_item12.isSelected)
                {
                    canSelect= DataModel.getInstance().isqtc
                }

                bundle.putBoolean("canSelectBiao",canSelect)
                bundle.putBoolean("canInput", true)
                bundle.putInt("goodsType", 2)
                intent.putExtras(bundle)
                startActivityForResult(intent, CHOOSE_GOODS_NAME)
            }
            R.id.text_sendCom -> {
                if (isCanChooseSendCom) {
                    val intent = Intent(this, SearchActivity::class.java)
                    bundle.putInt("type", CHOOSE_SEND_COM_NAME)
                    bundle.putBoolean("canInput", "按单位名称/编码搜索或直接输入" == text_sendCom.hint)
                    intent.putExtras(bundle)
                    startActivityForResult(intent, CHOOSE_SEND_COM_NAME)
                } else {
                    toast("货物名称选择标证除皮时，不能选择发货单位!")
                }

            }
            R.id.text_receiptCom -> {
                if (isCanChooseReceiptCom) {
                    val intent = Intent(this, SearchActivity::class.java)
                    bundle.putInt("type", CHOOSE_RECEPT_COM_NAME)
                    bundle.putBoolean("canInput", "按单位名称/编码搜索或直接输入" == text_receiptCom.hint)
                    intent.putExtras(bundle)
                    startActivityForResult(intent, CHOOSE_RECEPT_COM_NAME)
                } else {
                    toast("货物名称选择标证除皮时，不能选择收货单位!")
                }
            }
            R.id.ll_btn1 -> {
                when (text_btn1.text) {
                    "下一步" -> {
                        if (text_goodsName.text.isNullOrEmpty()) {
                            toast("请选择或输入物资名称")
                            return
                        }
                        if (text_receiptCom.text.isNullOrEmpty()) {
                            toast("请选择或输入收货单位")
                            return
                        }
                        if (text_sendCom.text.isNullOrEmpty()) {
                            toast("请选择或输入发货单位")
                            return
                        }
                        showProgress("", true)
                        presenter?.checkUnit(text_sendCom.text.toString(), text_receiptCom.text.toString())
                    }
                    "上一步" -> {
                        step--
                        setDataCausedStep()
                    }
                }
            }
            R.id.ll_btn2 -> {

                if (text_label11.isSelected) {
                    requestData.measurementType = 1
                }
                if (text_label12.isSelected) {
                    requestData.measurementType = 2
                }
                if (text_label13.isSelected) {
                    requestData.measurementType = 4
                }
                if (text_label14.isSelected) {
                    requestData.measurementType = 5
                }
                if (text_label15.isSelected) {
                    requestData.measurementType = 6
                }
                if (rl_item21.isSelected) {
                    when (text_label21.text) {
                        "先重后空" -> {
                            requestData.measurementMethod = 1
                        }
                        "先空后重" -> {
                            requestData.measurementMethod = 2
                        }
                        "标证除皮" -> {
                            requestData.measurementMethod = 3
                        }
                        "标证办理" -> {
                            requestData.measurementMethod = 6
                        }
                    }
                }
                if (rl_item22.isSelected) {
                    when (text_label22.text) {
                        "先重后空" -> {
                            requestData.measurementMethod = 1
                        }
                        "先空后重" -> {
                            requestData.measurementMethod = 2
                        }
                        "标证除皮" -> {
                            requestData.measurementMethod = 3
                        }
                    }
                }
                if (rl_item23.isSelected) {
                    when (text_label23.text) {
                        "先重后空" -> {
                            requestData.measurementMethod = 1
                        }
                        "先空后重" -> {
                            requestData.measurementMethod = 2
                        }
                        "标证除皮" -> {
                            requestData.measurementMethod = 3
                        }
                    }
                }
                //物资名称
                requestData.materialName = text_goodsName.text.toString()
                //发货单位
                requestData.forwardingUnit = text_sendCom.text.toString()
                //收货单位
                requestData.receivingUnit = text_receiptCom.text.toString()
                //调度司机
                requestData.waybill = driverInfoList
                requestData.materialCode = orG_CODE
                requestData.waybill?.let {
                    for (item in it) {
                        if (item.carNum == null || item.driverName == null || item.driverPhone == null) {
                            toast("请完善司机信息")
                            return
                        }
                    }
                }
                PreRegisterDialog.Builder(this, requestData)
                        .setSureOnclickListener(object : PreRegisterDialog.SusreOnclickListener {
                            override fun onClick() {
                                showProgress("", true)
                                presenter?.createWaybill(requestData)
                            }
                        }).create().show()
            }
            R.id.rl_item11 -> {
                setLabelSelected(true, false, false, false, false)
            }
            R.id.rl_item12 -> {
                setLabelSelected(false, true, false, false, false)
            }
            R.id.rl_item13 -> {
                setLabelSelected(false, false, true, false, false)
            }
            R.id.rl_item14 -> {
                setLabelSelected(false, false, false, true, false)
            }
            R.id.rl_item15 -> {
                setLabelSelected(false, false, false, false, true)
            }

            R.id.rl_item21 -> {
                setLabelSelected1(true, false, false)
            }
            R.id.rl_item22 -> {
                setLabelSelected1(false, true, false)
            }
            R.id.rl_item23 -> {
                setLabelSelected1(false, false, true)
            }
        }
    }

    override fun createSucceed() {
        step = 3
        setDataCausedStep()
        //三秒后返回
        Timer().schedule(timerTask {
            returnActivity()
        }, 3 * 1000)
    }

    override fun createFailed(msg: String) {
        toast(msg)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            Activity.RESULT_OK -> {
                when (requestCode) {
                    CHOOSE_GOODS_NAME -> {
                        text_goodsName.text = data?.getStringExtra("input")
                        orG_CODE = data?.getStringExtra("orG_CODE")
                        data?.getBooleanExtra("isOutOfSkin", false)?.let {
                            isOutOfSkin = it
                        }
                        Log.i("TAG货物是否可以标证除皮", "isOutOfSkin" + isOutOfSkin)
                        if (isOutOfSkin) {
                            if (rl_item14.isSelected || rl_item15.isSelected) {
                                rl_item23.visibility = View.VISIBLE
                            }
                        } else {
                            rl_item23.visibility = View.INVISIBLE
                            setLabelSelected1(true, false, false)
                        }
                        //如果选择外购其他，用户为钢企球团厂，且选择的货物名为“标证办理”时，
                        //发货单位默认为“标证办理”不可修改，收货单位默认为“钢企球团厂”不可修改，计量方式默认为“标证办理”不可修改
                        if (DataModel.getInstance().isqtc && text_goodsName.text.toString() == "标证办理") {
                            setLabelSelected(false, true, false, false, false)
                            text_sendCom.text = "标证办理"
                            text_receiptCom.text = "钢企球团厂"
                            text_label21.text = "标证办理"
                            isCanChooseSendCom = false
                            isCanChooseReceiptCom = false
                        } else {
                            if (text_sendCom.text == "标证办理") {
                                text_sendCom.text = ""
                            }
                            if (text_receiptCom.text == "钢企球团厂") {
                                text_receiptCom.text = ""
                            }
                            if (text_label21.text == "标证办理") {
                                if (rl_item13.isSelected) {
                                    text_label21.text = "先空后重"
                                } else {
                                    text_label21.text = "先重后空"
                                }
                            }
                            isCanChooseSendCom = true
                            isCanChooseReceiptCom = true
                        }
                    }
                    CHOOSE_SEND_COM_NAME -> {
                        text_sendCom.text = data?.getStringExtra("input")
                    }
                    CHOOSE_RECEPT_COM_NAME -> {
                        text_receiptCom.text = data?.getStringExtra("input")
                    }
                    CHOOSE_DRIVER -> {
                        var driverPosition = -1
                        data?.getIntExtra("driverPosition", -1)?.let {
                            driverPosition = it
                        }
                        if (driverPosition != -1) {
                            var selectedDriver: SearchDriverBean? = data?.extras?.getSerializable("selectedDriver") as SearchDriverBean?
                            when (selectedDriver?.driverId) {
                                null, 0 -> {//没有搜索到司机，需要新增
                                    selectedDriver?.driverName?.let {
                                        driverInfoList[driverPosition].driverName = it
                                    }
                                    selectedDriver?.driverPhone?.let {
                                        driverInfoList[driverPosition].driverPhone = it
                                        presenter?.checkDriverPhone(it, selectedDriver?.driverName)
                                    }
                                }
                                else -> {
                                    driverInfoList[driverPosition].driverName = selectedDriver?.driverName
                                    driverInfoList[driverPosition].driverPhone = selectedDriver?.driverPhone
                                    selectedDriver?.driverPhone?.let {
                                        presenter?.checkDriverPhone(it, driverInfoList[driverPosition].driverName)
                                    }
//                                    driverInfoList[driverPosition].id = selectedDriver?.driverId
                                }
                            }
                            driverInfoAdapter.notifyItemChanged(driverPosition)
                        }
                    }
                }
            }
        }
    }

    override fun havePermission(havePermission: Boolean) {
        if (havePermission) {
            step++
            setDataCausedStep()
        } else {
            toast("您没有该发/收货单位的登记权限")
        }
    }

    //设置上一步、下一步页面变化
    private fun setDataCausedStep() {
        when (step) {
            1 -> {
                text_top1.setTextColor(application.resources.getColor(R.color.white))
                text_top21.setTextColor(application.resources.getColor(R.color.cfad646))
                text_top21.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view1.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                text_top2.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top22.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top22.setBackgroundResource(R.drawable.bg_gray_cycle)
                view2.setBackgroundColor(application.resources.getColor(R.color.cbababa))
                view3.setBackgroundColor(application.resources.getColor(R.color.cbababa))

                text_top3.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top23.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top23.setBackgroundResource(R.drawable.bg_gray_cycle)
                view4.setBackgroundColor(application.resources.getColor(R.color.cbababa))

                step1.visibility = View.VISIBLE
                step2.visibility = View.GONE
                step3.visibility = View.GONE

                text_btn1.text = "下一步"
                ll_btn2.visibility = View.GONE
                toolbar_right_text_view.visibility = View.GONE
            }
            2 -> {
                text_top1.setTextColor(application.resources.getColor(R.color.white))
                text_top21.setTextColor(application.resources.getColor(R.color.white))
                text_top21.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view1.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                text_top2.setTextColor(application.resources.getColor(R.color.white))
                text_top22.setTextColor(application.resources.getColor(R.color.cfad646))
                text_top22.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view2.setBackgroundColor(application.resources.getColor(R.color.cfad646))
                view3.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                text_top3.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top23.setTextColor(application.resources.getColor(R.color.cbababa))
                text_top23.setBackgroundResource(R.drawable.bg_gray_cycle)
                view4.setBackgroundColor(application.resources.getColor(R.color.cbababa))

                step1.visibility = View.GONE
                step2.visibility = View.VISIBLE
                step3.visibility = View.GONE

                text_btn1.text = "上一步"
                ll_btn2.visibility = View.VISIBLE
                toolbar_right_text_view.visibility = View.VISIBLE
            }
            3 -> {
                text_top1.setTextColor(application.resources.getColor(R.color.white))
                text_top21.setTextColor(application.resources.getColor(R.color.white))
                text_top21.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view1.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                text_top2.setTextColor(application.resources.getColor(R.color.white))
                text_top22.setTextColor(application.resources.getColor(R.color.cfad646))
                text_top22.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view2.setBackgroundColor(application.resources.getColor(R.color.cfad646))
                view3.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                text_top3.setTextColor(application.resources.getColor(R.color.white))
                text_top23.setTextColor(application.resources.getColor(R.color.cfad646))
                text_top23.setBackgroundResource(R.drawable.bg_yellow_cycle)
                view4.setBackgroundColor(application.resources.getColor(R.color.cfad646))

                step1.visibility = View.GONE
                step2.visibility = View.GONE
                step3.visibility = View.VISIBLE
                ll_bottom.visibility = View.GONE
                toolbar_right_text_view.visibility = View.GONE
            }
        }
    }

    //设置计量类别选中项
    private fun setLabelSelected(c1: Boolean, c2: Boolean, c3: Boolean, c4: Boolean, c5: Boolean) {
        rl_item11.isSelected = c1
        rl_item12.isSelected = c2
        rl_item13.isSelected = c3
        rl_item14.isSelected = c4
        rl_item15.isSelected = c5
        setTextColor(c1, text_label11, image_tick_11)
        setTextColor(c2, text_label12, image_tick_12)
        setTextColor(c3, text_label13, image_tick_13)
        setTextColor(c4, text_label14, image_tick_14)
        setTextColor(c5, text_label15, image_tick_15)
        if (c1) {
            text_label21.text = "先重后空"
            rl_item21.visibility = View.VISIBLE
            rl_item22.visibility = View.INVISIBLE
            rl_item23.visibility = View.INVISIBLE
            text_sendCom.hint = "按单位名称/编码搜索或直接输入"
            text_receiptCom.hint = "按单位名称/编码搜索"
            text_sendCom.text = ""
            text_receiptCom.text = ""
            setLabelSelected1(true, false, false)
        }
        if (c2) {
            text_label21.text = "先重后空"
            rl_item21.visibility = View.VISIBLE
            rl_item22.visibility = View.INVISIBLE
            rl_item23.visibility = View.INVISIBLE
            text_sendCom.hint = "按单位名称/编码搜索或直接输入"
            text_receiptCom.hint = "按单位名称/编码搜索"
            text_sendCom.text = ""
            text_receiptCom.text = ""
            setLabelSelected1(true, false, false)
        } else {
            if (text_goodsName.text.toString() == "标证办理") {
                text_goodsName.text = ""
            }
        }
        if (c3) {
            text_label21.text = "先空后重"
            rl_item21.visibility = View.VISIBLE
            rl_item22.visibility = View.INVISIBLE
            rl_item23.visibility = View.INVISIBLE
            text_sendCom.hint = "按单位名称/编码搜索"
            text_receiptCom.hint = "按单位名称/编码搜索或直接输入"
            text_sendCom.text = ""
            text_receiptCom.text = ""
            setLabelSelected1(true, false, false)
        }
        if (c4) {
            text_label21.text = "先重后空"
            text_label22.text = "先空后重"
            text_label23.text = "标证除皮"
            rl_item21.visibility = View.VISIBLE
            rl_item22.visibility = View.VISIBLE
            if (isOutOfSkin) {//被选择的物资允许标证除皮计量
                rl_item23.visibility = View.VISIBLE
            } else {
                rl_item23.visibility = View.INVISIBLE
            }
            text_sendCom.hint = "按单位名称/编码搜索"
            text_receiptCom.hint = "按单位名称/编码搜索"
            text_sendCom.text = ""
            text_receiptCom.text = ""
            setLabelSelected1(true, false, false)
        }
        if (c5) {
            text_label21.text = "先重后空"
            text_label22.text = "先空后重"
            text_label23.text = "标证除皮"
            rl_item21.visibility = View.VISIBLE
            rl_item22.visibility = View.VISIBLE
            if (isOutOfSkin) {//被选择的物资允许标证除皮计量
                rl_item23.visibility = View.VISIBLE
            } else {
                rl_item23.visibility = View.INVISIBLE
            }
            text_sendCom.hint = "按单位名称/编码搜索或直接输入"
            text_receiptCom.hint = "按单位名称/编码搜索或直接输入"
            text_sendCom.text = ""
            text_receiptCom.text = ""
            setLabelSelected1(true, false, false)
        }
    }

    //设置计量方式选中项
    private fun setLabelSelected1(c1: Boolean, c2: Boolean, c3: Boolean) {
        rl_item21.isSelected = c1
        rl_item22.isSelected = c2
        rl_item23.isSelected = c3
        setTextColor(c1, text_label21, image_tick_21)
        setTextColor(c2, text_label22, image_tick_22)
        setTextColor(c3, text_label23, image_tick_23)
    }

    private fun setTextColor(isChecked: Boolean, textView: TextView, imageView: ImageView) {
        when (isChecked) {
            true -> {
                textView.setTextColor(application.resources.getColor(R.color.black))
                imageView.visibility = View.VISIBLE
            }
            false -> {
                textView.setTextColor(application.resources.getColor(R.color.c999999))
                imageView.visibility = View.GONE
            }
        }
    }

    override fun showCheckCarNum(data: ValMsgDto, position: Int) {
        when (data.state) {
            1 -> { //1、正常(无需弹警告) 2、弹出警告(可以新增) 3、弹出警告（不让新增） ,
                driverInfoList[position].driverName = data.driverName
                driverInfoList[position].driverPhone = data.driverPhone
                driverInfoAdapter.notifyDataSetChanged()
            }
            2 -> {
                driverInfoList[position].driverName = data.driverName
                driverInfoList[position].driverPhone = data.driverPhone
                driverInfoAdapter.notifyDataSetChanged()
                showDialog(data.msg, DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            }
            3 -> {
                showDialog(data.msg, DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                    val utils = LicensePlateUtils(this@PreRegisterActivity, popupWindow)
                    utils.showInParentDown(ll_step2)
                    utils.setLicenseSelectedListener { licenseNum ->
                        driverInfoList[position].carNum = licenseNum
                        presenter?.checkCarNum(licenseNum, position)
                        driverInfoAdapter.notifyDataSetChanged()
                    }
                }, null)
            }
        }
    }

    override fun showCheckDriverPhone(isNew: Boolean, phone: String, name: String?) {
        if (isNew) {
            if (name == null || name == "") {
                showDialog("该驾驶员为系统新增的驾驶员，请您务必告知该驾驶员在登录卡车帮app时，默认登录账号为" + phone + "，登录密码为666666!", DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            } else {
                showDialog("驾驶员" + name + "为系统新增的驾驶员，请您务必告知该驾驶员在登录卡车帮app时，默认登录账号为+" + phone + "，登录密码为666666!", DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            }

        }
    }

}
